<!-- 文件上传 -->
<template>
  <div class="el-upload-wrapper">
    <el-upload :before-upload="handleBeforeUpload" :http-request="uploadFile" drag multiple>
      <div class="upload-body">
        <img src="../../../assets/images/w01.png" alt="" />
        <div class="el-upload__text">
          <div><em>点击上传，</em>或者拖动文档到这里</div>
          <div class="el-upload__tip">
            <slot></slot>文件小于 200mb
          </div>
        </div>
      </div>
    </el-upload>
    <div class="line"></div>
    <div body-class="fix-width">
      <el-table v-loading="loading" :data="fileList" class="fix-table" fixed :show-header="false" :style="{
        '--el-table-border': 'transparent',
        '--el-table-border-color': 'transparent',
      }">
        <el-table-column type="index" width="50" align="center" />
        <el-table-column prop="fileName" label="文件名" align="center" />
        <el-table-column key="oper" width="100" label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="handleDelete(scope.row)"><i-ep-delete />删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { UploadRawFile, UploadRequestOptions } from "element-plus";
import { uploadFileApi, deleteFileApi } from "@/api/ai/chat/index";
import { DeleteFileQuery } from "@/api/ai/chat/types";
import { deleteKnowledgeFile } from "@/api/ai/knowledge-file/index";

import {
  KnowledgeFileForm,
  KnowledgeFileQuery,
  KnowledgeFileVO,
} from "@/api/ai/knowledge-file/types";
import {
  saveKnowledgeFile,
  listKnowledgeFile,
} from "@/api/ai/knowledge-file/index";

const props = defineProps({
  params: {
    // KnowledgeFileQuery 类型
    type: Object,
    default: () => { },
  },
  beforeUpload: {
    type: Function,
    default: () => {
      return true;
    },
  },
});

const loading = ref(false);
const fileList = ref<KnowledgeFileVO[]>([]);

// 上传文档到 python 后台服务器
async function uploadFile(options: UploadRequestOptions): Promise<any> {
  await uploadFileApi(options.file, {
    knowledgeId: props.params.knowledgeId,
  });
  saveKnowledgeInfo(options.file.name);
}

// 保存已上传的文档信息到本地后台
function saveKnowledgeInfo(filename: string) {
  const queryParams = props.params as KnowledgeFileQuery;
  const params: KnowledgeFileForm = {
    fileName: filename,
    knowledgeId: queryParams.knowledgeId,
    category: queryParams.category,
  };
  saveKnowledgeFile(params).then(() => {
    loadData();
  });
}

// 上传前校验大小
function handleBeforeUpload(file: UploadRawFile) {
  if (!props.params.knowledgeId) {
    ElMessage.warning("页面出错，请刷新");
    return false;
  }
  if (file.size > 200 * 1048 * 1048) {
    ElMessage.warning("上传图片不能大于200M");
    return false;
  }

  return props.beforeUpload(file);
}

// 删除文件记录
function handleDelete(data) {
  ElMessageBox.confirm("确定要删除文件吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    const params: DeleteFileQuery = {
      knowledge_base_id: data.knowledgeId,
      doc_name: data.fileName,
    };
    // 先删除知识库文件
    deleteFileApi(params)
      .then((res) => {
        // 删除后台文件
        deleteKnowledgeFile([data.id]).then(() => {
          loadData();
          ElMessage.success("删除成功");
        });
      })
      .catch((code) => {
        // 远程和本地不同步问题
        if (code == 404) {
          deleteKnowledgeFile([data.id]).then(() => {
            loadData();
          });
        }
      });
  });
}

// 加载文件
function loadData() {
  const queryParams = props.params as KnowledgeFileQuery;
  listKnowledgeFile(queryParams).then(({ data }) => {
    fileList.value = data;
  });
}

onMounted(() => {
  loadData();
});
</script>

<style lang="scss" scoped>
.el-upload-wrapper {
  display: flex;
  flex-direction: column;

  :deep(.el-upload) {
    --el-upload-dragger-padding-horizontal: 0px;
    --el-upload-dragger-padding-vertical: 0px;

    .el-upload-dragger {
      border: none;
    }
  }

  .upload-body {
    display: flex;
    justify-content: center;

    .el-upload__text {
      margin-top: 10px;
      margin-left: 10px;
    }

    .el-upload__tip {
      text-align: left;
      color: var(--el-color-info-dark-2);
    }
  }
}

.line {
  height: 1px; //必须写高度
  width: 100%;
  background-image: linear-gradient(to right,
      rgba(93, 147, 252, 0.7) 60%,
      rgba(255, 255, 255, 0) 0%);
  background-position: bottom;
  background-size: 14px 2px;
  background-repeat: repeat-x;
  margin: 20px 0;
}
</style>
